<html>
<head>
<script>
var animationFrames = 36;
var animationSpeed = 10; // ms
var canvas;
var canvasContext;
var version = '0.5';
var options_updated = true;
var gwave = "";
var gwaveRef = "";
var loggedInImage;
var pollInterval = (1000 * 60) * 5;  // 5 minutes
var requestTimeout = 1000 * 10;  // 10 seconds
var rotation = 0;
var unreadCount = -1;
var loadingAnimation = new LoadingAnimation();

// A "loading" animation displayed while we wait for the first response from
// Google Wave. This animates the badge text with a dot that cycles from left to
// right.
function LoadingAnimation() {
  this.timerId_ = 0;
  this.maxCount_ = 8;  // Total number of states in animation
  this.current_ = 0;  // Current state
  this.maxDot_ = 4;  // Max number of dots in animation
}

LoadingAnimation.prototype.paintFrame = function() {
  var text = "";
  for (var i = 0; i < this.maxDot_; i++) {
    text += (i == this.current_) ? "." : " ";
  }
  if (this.current_ >= this.maxDot_)
    text += "";
  chrome.browserAction.setBadgeText({text:text});
  this.current_++;
  if (this.current_ == this.maxCount_)
    this.current_ = 0;
}

LoadingAnimation.prototype.start = function() {
  if (this.timerId_)
    return;
  var self = this;
  this.timerId_ = window.setInterval(function() {
    self.paintFrame();
  }, 100);
}

LoadingAnimation.prototype.stop = function() {
  if (!this.timerId_)
    return;
  window.clearInterval(this.timerId_);
  this.timerId_ = 0;
}

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
  if (changeInfo.url && changeInfo.url.indexOf(gwave) == 0) {
    console.log("saw google wave! updating...");
    getInboxCount(function(count) {
      updateUnreadCount(count);
    });
  }
});

function init() {
  if (localStorage["version"] == null || localStorage["version"] != version) {
    localStorage["version"] = version;
    if (options_updated)
      chrome.tabs.create({url : "options.html"});        
  }
  canvas = document.getElementById('canvas');
  loggedInImage = document.getElementById('logged_in');
  canvasContext = canvas.getContext('2d');
  chrome.browserAction.setIcon({path: "wn_logged_in.gif"});
  loadingAnimation.start();
  setWaveDomain();  
  startRequest();
}

function refresh() {
  init();
}

function setWaveDomain() {
  if(localStorage["wave_domain"] != null && localStorage["wave_domain"].length > 0)
      gwave = localStorage["wave_domain"];
  else gwave = "https://wave.google.com/wave";
  gwaveRef = gwave + "/?nouacheck&ua=wavenotifierforchrome";
}

function scheduleRequest() {
  window.setTimeout(startRequest, pollInterval);
}

// ajax stuff
function startRequest() {
  getInboxCount(
    function(count) {
      loadingAnimation.stop();
      updateUnreadCount(count);
      scheduleRequest();
    },
    function() {
      loadingAnimation.stop();
      showLoggedOut();
      scheduleRequest();
    }
  );
}

function getInboxCount(onSuccess, onError) {
  var xhr = new XMLHttpRequest();
  var abortTimerId = window.setTimeout(function() {
    xhr.abort();
    onError();
  }, requestTimeout);

  function handleSuccess(count) {
    window.clearTimeout(abortTimerId);
    if (onSuccess)
      onSuccess(count);
  }

  function handleError() {
    window.clearTimeout(abortTimerId);
    if (onError)
      onError();
  }

  try {
    console.log("request..");
    xhr.onreadystatechange = function(){
      console.log("readystate: " + xhr.readyState);
      if (xhr.readyState == 4) {
        console.log("responseText: " + xhr.responseText.substring(0, 200) +
                    "...");
        if (xhr.responseText) {
          //search for the json containing all the waves
          var content = xhr.responseText.match(/var json = (\{"r":"\^d1".*});/);
          //two declaration of "r":"^d1" in source so we skip the first one
          if(content) {
            var gwave_details = JSON.parse(content[1].replace('var json = ', ''));
            var waves = gwave_details.p['1'];
            var count = 0;
            var n;
            var passed = false;
            for(i in waves) {
              if(waves[i]['7'] > 0) {
                passed = true;
                count+=1;
              }
            }            
            if (passed) {
              console.log("Number found " + count);
              handleSuccess(count);
            } else {
              console.log("Nothing found, no messages.");
              handleSuccess(0);
            }
          } else{
            console.log("Not logged in?");
            console.error("Error: Not logged in?");
            handleError();
          }
        } else {
          console.log("No responseText!");
        }
      }
    }

    xhr.onerror = function(error) {
      console.log("error");
      console.log(error);
      handleError();
    }

    xhr.open("GET", gwaveRef, true);
    xhr.send(null);
  } catch(e) {
    console.log("ex: " + e);
    console.error("exception: " + e);
    handleError();
  }
}

function updateUnreadCount(count) {
  if (unreadCount != count) {
    unreadCount = count;
    animateFlip();
  }
}

function ease(x) {
  return (1-Math.sin(Math.PI/2+x*Math.PI))/2;
}

function animateFlip() {
  rotation += 1/animationFrames;
  drawIconAtRotation();  
  if (rotation <= 1) {
    setTimeout("animateFlip()", animationSpeed);
  } else {
    rotation = 0;
    drawIconAtRotation();
    chrome.browserAction.setBadgeText({
      text: unreadCount != "0" ? unreadCount : ""
    });
    chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
  }
}

function showLoggedOut() {
  unreadCount = -1;
  chrome.browserAction.setIcon({path:"wn_not_logged_in.gif"});
  chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
  chrome.browserAction.setBadgeText({text:"?"});
}

function drawIconAtRotation() {
  canvasContext.save();
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  canvasContext.translate(
      Math.ceil(canvas.width/2),
      Math.ceil(canvas.height/2));
  canvasContext.rotate(2*Math.PI*ease(rotation));

  var img = loggedInImage;
  chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
  switch(unreadCount)
  {
    case 0:
	      chrome.browserAction.setTitle({title:"No unread waves"});
	      chrome.browserAction.setBadgeText({text:""});
        break;
    case 1:
	      chrome.browserAction.setTitle({title:"1 unread wave"});
	      chrome.browserAction.setBadgeText({text:unreadCount+""});
        break;
    default:   
        chrome.browserAction.setTitle({title:unreadCount + " unread waves"});
	      chrome.browserAction.setBadgeText({text:unreadCount+""});
        break;
  }

  canvasContext.drawImage(loggedInImage, 
      -Math.ceil(canvas.width/2),
      -Math.ceil(canvas.height/2));
  canvasContext.restore();

  chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0,
      canvas.width,canvas.height)});
}

function goToInbox() {
  chrome.tabs.create({url: gwave});
}

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  goToInbox();
});

</script>
</head>
<body onload="init()">
<img id="logged_in" src="wn_logged_in.gif">
<canvas id="canvas" width="19" height="19">
</body>
</html>

